<template>
  <Dialog :title="t('interview.index.selectStudent')" v-model="dialogVisible" width="1400">
    <!-- 列表 -->
    <ContentWrap>
      <vxe-table
        ref="tableRef"
        :data="list"
        stripe
        :column-config="{ resizable: true }"
        :size="vxeTableSize"
      >
        <vxe-column
          :title="t('student.fields.studentName')"
          field="studentName"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
          fixed="left"
        />
        <vxe-column
          :title="t('student.fields.phone')"
          field="phone"
          align="center"
          show-header-overflow
          show-overflow
          min-width="120"
        />
        <vxe-column
          :title="t('student.fields.batchId')"
          field="batchId"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        >
          <template #default="scope">
            {{ batchOptions.find((item) => item.id === scope.row.batchId)?.batchName }}
          </template>
        </vxe-column>
        <vxe-column
          :title="t('student.fields.interviewTime')"
          field="interviewTime"
          align="center"
          show-header-overflow
          show-overflow
          min-width="120"
        />
        <vxe-column
          :title="t('student.fields.interviewSelected')"
          field="interviewSelected"
          align="center"
          show-header-overflow
          show-overflow
          min-width="130"
        >
          <template #default="scope">
            {{ scope.row.interviewSelected ? t('common.yes') : t('common.no') }}
          </template>
        </vxe-column>
        <vxe-column
          :title="t('student.fields.interviewSlotTime')"
          field="interviewSlotTime"
          align="center"
          show-header-overflow
          show-overflow
          min-width="200"
        >
          <template #default="scope">
            <el-select
              v-model="scope.row.interviewSlotId"
              clearable
              @change="handleSlotChange($event, scope.row)"
            >
              <el-option
                v-for="(item, index) in slotList"
                :key="index"
                :label="item.startTime + '-' + item.endTime"
                :value="item.id"
                :disabled="list.some((student) => student.interviewSlotId === item.id)"
              />
            </el-select>
          </template>
        </vxe-column>
        <vxe-column
          :title="t('student.fields.university')"
          field="university"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        />
        <vxe-column
          :title="t('student.fields.is985')"
          field="is985"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
          :formatter="vxeBooleanFormatter"
        />
        <vxe-column
          :title="t('student.fields.is211')"
          field="is211"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
          :formatter="vxeBooleanFormatter"
        />
        <vxe-column
          :title="t('student.fields.isFirstClass')"
          field="isFirstClass"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
          :formatter="vxeBooleanFormatter"
        />
        <vxe-column
          :title="t('student.fields.studyMajor')"
          field="studyMajor"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        />
        <vxe-column
          :title="t('student.fields.applyMajor')"
          field="applyMajor"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        />
      </vxe-table>
    </ContentWrap>

    <template #footer>
      <el-button @click="handleNext" type="primary">{{ t('common.ok') }}</el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { StudentVO } from '@/api/recruit/recruitstudent'
import type { VxeTableInstance } from 'vxe-table'
import { useAppStore } from '@/store/modules/app'
import { BatchApi, BatchVO } from '@/api/recruit/batch'
import { InterviewGroupVO } from '@/api/recruit/interviewgroup'
import { InterviewVO } from '@/api/recruit/interview'
import { InterviewSlotApi, InterviewSlotVO } from '@/api/recruit/interviewslot'
import _ from 'lodash-es'
import { vxeBooleanFormatter } from '@/utils/formatter'

/** 报名学生 列表 */
defineOptions({ name: 'RecruitStudentSetSlotStep3' })

const props = defineProps<{
  // 接收面试信息 用来查询面试下的所有slot
  interviewInfo: InterviewVO
}>()

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const tableRef = ref<VxeTableInstance>()

const list = ref<StudentVO[]>([]) // 列表的数据
const dialogVisible = ref(false)

const emits = defineEmits<{
  (e: 'next', value: StudentVO[]): void
}>()

const appStore = useAppStore()
const vxeTableSize = computed(() => appStore.getCurrentSizeVxe)

const formLoading = ref(false)

const batchOptions = ref<BatchVO[]>([])
const getBatchSelectOptions = async () => {
  batchOptions.value = await BatchApi.getSelectList()
}

const slotList = ref<InterviewSlotVO[]>([])
const getSlotList = async () => {
  slotList.value = await InterviewSlotApi.getInterviewSlotSelectListByInterviewId(
    props.interviewInfo.id
  )
}

// 面试管理-设置分组 新增第三步 自动分配slot
const open = async (group: InterviewGroupVO, students: StudentVO[]) => {
  list.value = students
  dialogVisible.value = true

  await getSlotList()

  if (!group.id) {
    // 新增的时候 随机分批slot
    const slots = _.cloneDeep(slotList.value)
    // 遍历每个学生，自动分配slot
    for (const student of list.value) {
      let expectSlots: InterviewSlotVO[]
      if (student.interviewTime === '上午') {
        // 从slots中随机取出一个'上午'的 如果没有 则取下午
        expectSlots = slots.filter((item) => item.daytime === '上午')
      } else {
        // 从slots中随机取出一个'下午'的 如果没有 则取上午
        expectSlots = slots.filter((item) => item.daytime === '下午')
      }
      if (expectSlots.length === 0) {
        expectSlots = slots
      }
      let randomSlot: InterviewSlotVO
      // 随机选择一个元素
      if (expectSlots.length > 0) {
        const randomIndex = Math.floor(Math.random() * expectSlots.length)
        randomSlot = expectSlots[randomIndex]

        // 从原数组中移除该元素
        const index = slots.findIndex((item) => item.id === randomSlot.id)
        slots.splice(index, 1)
      }

      if (randomSlot) {
        student.interviewSelected = true
        student.interviewSlotId = randomSlot.id
        student.interviewSlotTime = randomSlot.startTime + '-' + randomSlot.endTime
      }
    }
  }
}

const handleSlotChange = (value: number, row: StudentVO) => {
  const slot = slotList.value.find((item) => item.id === value)
  if (slot) {
    row.interviewSlotTime = slot.startTime + '-' + slot.endTime
  }
}

const handleNext = () => {
  // 校验所有人都被分配了slot
  list.value.some((item) => {
    if (!item.interviewSelected) {
      message.error(t('interview.index.selectSlotForAll'))
      return true
    }
  })

  emits('next', list.value)
  dialogVisible.value = false
  list.value = []
}

/** 初始化 **/
onMounted(async () => {
  // 查询所有计划
  await getBatchSelectOptions()
})

defineExpose({
  open
})
</script>

<style lang="scss" scoped>
:deep(.vxe-cell--checkbox.is--disabled) {
  .vxe-table-icon-checkbox-unchecked:before {
    content: '\e67d';
  }
}
</style>
